package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.CataAuctionItem;
import artid.com.arttogo.bean.CataOrganizationItem;
import artid.com.arttogo.bean.CataSpecialItem;
import artid.com.arttogo.bean.CatalogueBean;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.task.CallbackSky;
import artid.com.arttogo.utils.DownloadUtil;
import artid.com.arttogo.utils.MyBitmapImageViewTarget;
import artid.com.arttogo.utils.NetUtils;

public class AuctionCatalogueActivity extends Activity {
    private Context mContext;
    private TextView my;
    private ImageView back;
    /**
     * --------------机构列表------------------
     */
    private GridView Organizationlist;
    private OrganizationAdapter jgAdapter;
    private String organizationInfo;
    /**
     * 机构数据
     */
    private ArrayList<CataOrganizationItem> list = new ArrayList<CataOrganizationItem>();

    /**
     * -------------- 拍卖会列表 --------------
     */
    private GridView Auctionlist;
    private String auctionInfo;
    private AuctionAdapter pmAdapter;
    /**
     * 拍卖会数据
     */
    private ArrayList<CataAuctionItem> pmlist = new ArrayList<CataAuctionItem>();
    private RelativeLayout relAuction;

    /**
     * --------------专场列表 --------------
     */
    private ListView Speciallist;
    private String specialInfo;
    private SpecialAdapter zcAdapter;
    /**
     * 专场数据
     */
    private ArrayList<CataSpecialItem> zclist = new ArrayList<CataSpecialItem>();
    private RelativeLayout relSpecial;
    /**
     * 描述目录
     */
    private TextView catalog;
    /**
     * 层级
     */
    private int hier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auctioncatalogue_list);
        ArtToGoApp.setActivity(this);
        initView();
        requestJG();
    }

    private void initView() {
        // TODO Auto-generated method stub
        mContext = this;
        Organizationlist = (GridView) findViewById(R.id.cata_jg_grid);
        Auctionlist = (GridView) findViewById(R.id.cata_pmh_grid);
        Speciallist = (ListView) findViewById(R.id.cata_zc_list);
        catalog = (TextView) findViewById(R.id.tv_catalog);

        my = (TextView) findViewById(R.id.tv_mytulu);
        relAuction = (RelativeLayout) findViewById(R.id.rel_pmh);
        relSpecial = (RelativeLayout) findViewById(R.id.rel_zc);
        my.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent in = new Intent(mContext, MyCatalogueActivity.class);
                startActivity(in);
            }
        });
        back = (ImageView) findViewById(R.id.back_btn);
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();

            }
        });
    }

    private int organizationID;
    private int organizationIndex;

    /**
     * 机构列表适配器
     *
     * @author XiongBin
     */
    class OrganizationAdapter extends BaseAdapter {
        private ArrayList<CataOrganizationItem> list;

        public OrganizationAdapter(ArrayList<CataOrganizationItem> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
        }

        void refreshAdapter(ArrayList<CataOrganizationItem> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public View getView(final int index, View convertView, ViewGroup arg2) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(),
                        R.layout.item_organization, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            final CataOrganizationItem coi = list.get(index);
            System.out.println(coi.toString());
            if (coi != null) {
                holder.title.setText(coi.getSeller_name());
                Glide.with(mContext).load(coi.getLogo()).asBitmap()
                        .centerCrop().placeholder(R.drawable.tu_bg)
                        .error(R.drawable.tu_bg)
                        .into(new MyBitmapImageViewTarget(holder.logo));
            }
            holder.logo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    organizationID = Integer.parseInt(coi.getId());
                    organizationIndex = index;
                    requestPMH(coi.getId());
                    // setShowAnimation(relAuction, 500);
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView title;
            ImageView logo;

            public ViewHolder(View view) {
                title = (TextView) view.findViewById(R.id.tv_title);
                logo = (ImageView) view.findViewById(R.id.iv_logo);
                view.setTag(this);
            }
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public CataOrganizationItem getItem(int arg0) {
            // TODO Auto-generated method stub
            return list.get(arg0);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }
    }

    ;

    private int auctionIndex;
    private int auctionID;

    /**
     * 拍卖会列表适配器
     *
     * @author XiongBin
     */
    class AuctionAdapter extends BaseAdapter {
        private ArrayList<CataAuctionItem> list;

        public AuctionAdapter(ArrayList<CataAuctionItem> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
        }

        void refreshAdapter(ArrayList<CataAuctionItem> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public View getView(final int index, View convertView, ViewGroup arg2) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(),
                        R.layout.item_auction, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            final CataAuctionItem coi = list.get(index);
            System.out.println(coi.toString());
            if (coi != null) {
                holder.title.setText(coi.getTitle());
                holder.specialNum.setText(coi.getSpecial_num() + "个专场");
                holder.lotNum.setText(coi.getLot_num() + "件拍品");
                holder.data.setText(coi.getAuction_start_time());
                Glide.with(mContext).load(coi.getImgurl())
                        .placeholder(R.drawable.tu_bg).error(R.drawable.tu_bg)
                        .into(holder.logo);
            }
            holder.logo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    auctionID = Integer.parseInt(coi.getId());
                    auctionIndex = index;
                    requestZC(coi.getId());
                    // setShowAnimation(relAuction, 500);
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView title, specialNum, lotNum, data;
            ImageView logo;

            public ViewHolder(View view) {
                title = (TextView) view.findViewById(R.id.tv_title);
                specialNum = (TextView) view.findViewById(R.id.tv_special_num);
                lotNum = (TextView) view.findViewById(R.id.tv_lot_num);
                data = (TextView) view.findViewById(R.id.tv_data);
                logo = (ImageView) view.findViewById(R.id.iv_logo);
                view.setTag(this);
            }
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public CataAuctionItem getItem(int arg0) {
            // TODO Auto-generated method stub
            return list.get(arg0);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }
    }

    ;

    /**
     * 专场列表适配器
     *
     * @author XiongBin
     */
    class SpecialAdapter extends BaseAdapter {
        private ArrayList<CataSpecialItem> list;

        public SpecialAdapter(ArrayList<CataSpecialItem> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
        }

        void refreshAdapter(ArrayList<CataSpecialItem> list) {
            // TODO Auto-generated constructor stub
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public View getView(int index, View convertView, ViewGroup arg2) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(),
                        R.layout.item_special, null);
                new ViewHolder(convertView);
            }
            final ViewHolder holder = (ViewHolder) convertView.getTag();
            final CataSpecialItem coi = list.get(index);
            System.out.println(coi.toString());
            if (coi != null) {
                holder.title.setText(coi.getTitle());
                holder.data.setText("拍卖时间：" + coi.getAuction_start_time() + "-"
                        + coi.getAuction_end_time());
                holder.specialNum.setText(coi.getLotrecord_num() + "件备案/"
                        + coi.getLot_num() + "件拍品");
                holder.mechanism.setText(coi.getSeller_name());
                Glide.with(mContext).load(coi.getImgurl())
                        .placeholder(R.drawable.tu_bg).error(R.drawable.tu_bg)
                        .into(holder.logo);
                String name = organizationID + auctionID + coi.getId();
                String path = DownloadUtil.baseUrl + name + ".zip";
                if (fileIsExists(path)) {
                    holder.load.setText("已下载");
                    holder.load.setEnabled(false);
                    holder.load.setTextColor(mContext.getResources().getColor(
                            R.color.yxiazai));
                } else if (fileIsExists(path + ".tmp")) {
                    holder.load.setText("正在下载");
                    holder.load.setEnabled(false);
                    holder.load.setTextColor(mContext.getResources().getColor(
                            R.color.zxiazai));
                } else {
                    holder.load.setText("下载");
                    holder.load.setEnabled(true);
                    holder.load.setTextColor(mContext.getResources().getColor(
                            R.color.xiazai));
                }
            }

            holder.load.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    workcoi = coi;
                    new Thread(networkTask).start();
                    holder.load.setText("正在下载");
                    holder.load.setEnabled(false);
                }
            });
            holder.logo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent in = new Intent(mContext,
                            CatalogueDetailsActivity.class);
                    in.putExtra("type", DownloadUtil.NOTE_ONLINE);
                    in.putExtra("url", coi.getHtmlurl());
                    in.putExtra("imageurl", coi.getImgurl());
                    in.putExtra("content",
                            coi.getSeller_name() + "\n拍卖时间："
                                    + coi.getAuction_start_time() + "-"
                                    + coi.getAuction_end_time());
                    in.putExtra("surl", coi.getHtmlurl());
                    startActivity(in);
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView title, specialNum, mechanism, data, load;
            ImageView logo;

            public ViewHolder(View view) {
                title = (TextView) view.findViewById(R.id.tv_title);
                load = (TextView) view.findViewById(R.id.tv_load);
                data = (TextView) view.findViewById(R.id.tv_special_data);
                specialNum = (TextView) view.findViewById(R.id.tv_lot_num);
                mechanism = (TextView) view.findViewById(R.id.tv_jg);
                logo = (ImageView) view.findViewById(R.id.iv_logo);
                view.setTag(this);
            }
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public CataSpecialItem getItem(int arg0) {
            // TODO Auto-generated method stub
            return list.get(arg0);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }
    }

    ;

    public CataSpecialItem workcoi;

    /**
     * 请求机构列表
     */
    void requestJG() {

        RequestParams params = new RequestParams(Cache.jigoucatalogList);
        params.addHeader("Accept", "application/json, text/javascript, */*");
        // try {
        params.addParameter("pagesize", 2);
        // JSONArray a = new JSONArray();
        // JSONObject o = new JSONObject();
        // o.put("pagesize", 2);
        // a.put(o);
        // params.addBodyParameter("data", a.toString());
        // } catch (JSONException e1) {
        // // TODO Auto-generated catch block
        // e1.printStackTrace();
        // }
        x.http().post(params, new CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {
                // TODO Auto-generated method stub
                System.out.println("主动停止网络请求");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // TODO Auto-generated method stub
                // 请求错误
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub

                System.out.println("请求完毕,不管成功失败");
            }

            @Override
            public void onSuccess(String result) {
                // TODO Auto-generated method stub
                // 成功
                result = NetUtils.decodeUnicode(result);
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject baseOb = new JSONObject(result);
                        String msg = baseOb.optString("msg");
                        String ret = baseOb.optString("ret");
                        if (ret.equals("1")) {
                            list.clear();
                            JSONArray dataOB = baseOb.optJSONArray("data");
                            for (int i = 0; i < dataOB.length(); i++) {
                                JSONObject ob = dataOB.getJSONObject(i);
                                CataOrganizationItem or = new CataOrganizationItem();
                                or.parse(ob);
                                list.add(or);
                            }
                            organizationInfo = "机构(" + dataOB.length() + ")";
                            catalog.setText(organizationInfo);
                            if (jgAdapter == null) {
                                jgAdapter = new OrganizationAdapter(list);
                                Organizationlist.setAdapter(jgAdapter);
                            } else {
                                jgAdapter.refreshAdapter(list);
                            }
                            hier = 1;
                        } else {
                            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("result=" + result);
            }
        });
    }

    /**
     * 请求拍卖行列表
     */
    void requestPMH(final String id) {
        RequestParams params = new RequestParams(Cache.auclogList);
        params.addHeader("Accept", "application/json, text/javascript, */*");
        // try {
        params.addParameter("id", id);
        x.http().post(params, new CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {
                // TODO Auto-generated method stub
                System.out.println("主动停止网络请求");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // TODO Auto-generated method stub
                // 请求错误
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub

                System.out.println("请求完毕,不管成功失败");
            }

            @Override
            public void onSuccess(String returnString) {
                // TODO Auto-generated method stub
                // 成功
                returnString = NetUtils.decodeUnicode(returnString);
                if (!TextUtils.isEmpty(returnString)) {
                    try {
                        JSONObject baseOb = new JSONObject(returnString);
                        String msg = baseOb.optString("msg");
                        String ret = baseOb.optString("ret");
                        if (ret.equals("1")) {
                            pmlist.clear();
                            JSONArray dataOB = baseOb
                                    .optJSONArray("data");
                            for (int i = 0; i < dataOB.length(); i++) {
                                JSONObject ob = dataOB.getJSONObject(i);
                                CataAuctionItem or = new CataAuctionItem();
                                or.parse(ob);
                                pmlist.add(or);
                            }
                            organizationInfo = list.get(
                                    organizationIndex).getSeller_name();
                            auctionInfo = "拍卖行(" + dataOB.length()
                                    + ")";
                            catalog.setText(organizationInfo + "/"
                                    + auctionInfo);

                            if (pmAdapter == null) {
                                pmAdapter = new AuctionAdapter(pmlist);
                                Auctionlist.setAdapter(pmAdapter);
                            } else {
                                pmAdapter.refreshAdapter(pmlist);
                            }
                            setShowAnimation(relAuction, 500);
                            hier = 2;
                        } else {
                            Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
                        }

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("result=" + returnString);
            }
        });
    }

    /**
     * 请求专场列表
     */
    void requestZC(final String id) {
        {
            RequestParams params = new RequestParams(Cache.spLogList);
            params.addHeader("Accept", "application/json, text/javascript, */*");
            // try {
            params.addParameter("id", id);
            x.http().post(params, new CommonCallback<String>() {

                @Override
                public void onCancelled(CancelledException cex) {
                    // TODO Auto-generated method stub
                    System.out.println("主动停止网络请求");
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    // TODO Auto-generated method stub
                    // 请求错误
                }

                @Override
                public void onFinished() {
                    // TODO Auto-generated method stub

                    System.out.println("请求完毕,不管成功失败");
                }

                @Override
                public void onSuccess(String returnString) {
                    // TODO Auto-generated method stub
                    // 成功
                    returnString = NetUtils.decodeUnicode(returnString);
                    if (!TextUtils.isEmpty(returnString)) {
                        try {
                            JSONObject baseOb = new JSONObject(returnString);
                            String msg = baseOb.optString("msg");
                            String ret = baseOb.optString("ret");
                            if (ret.equals("1")) {
                                zclist.clear();
                                JSONArray dataOB = baseOb
                                        .optJSONArray("data");
                                for (int i = 0; i < dataOB.length(); i++) {
                                    JSONObject ob = dataOB.getJSONObject(i);
                                    CataSpecialItem or = new CataSpecialItem();
                                    or.parse(ob);
                                    zclist.add(or);
                                }
                                auctionInfo = pmlist.get(auctionIndex)
                                        .getTitle();
                                specialInfo = "专场(" + zclist.size() + ")";
                                catalog.setText(organizationInfo + "/"
                                        + auctionInfo + "/" + specialInfo);

                                if (zcAdapter == null) {
                                    zcAdapter = new SpecialAdapter(zclist);
                                    Speciallist.setAdapter(zcAdapter);
                                } else {
                                    zcAdapter.refreshAdapter(zclist);
                                }
                                DownloadUtil.getInstance()
                                        .setListCallbackSky(
                                                new CallbackSky() {

                                                    @Override
                                                    public void callBack() {
                                                        // TODO
                                                        // Auto-generated
                                                        // method stub
                                                        if (zcAdapter != null)
                                                            zcAdapter
                                                                    .notifyDataSetChanged();
                                                    }
                                                });
                                setShowAnimation(relSpecial, 500);
                                hier = 3;
                            } else {
                                Toast.makeText(mContext, msg, Toast.LENGTH_LONG).show();
                            }

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("result=" + returnString);
                }
            });
        }
    }

    private AlphaAnimation mHideAnimation = null;
    private AlphaAnimation mShowAnimation = null;

    /**
     * View渐隐动画效果
     */
    private void setHideAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }
        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        // mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                view.clearAnimation();
                if (view.getId() == R.id.rel_pmh) {
                    pmlist.clear();
                    pmAdapter = null;
                    relAuction.setVisibility(View.GONE);
                } else if (view.getId() == R.id.rel_zc) {
                    zclist.clear();
                    zcAdapter = null;
                    relSpecial.setVisibility(View.GONE);
                }
            }
        });
        view.startAnimation(mHideAnimation);
    }

    /**
     * View渐现动画效果
     */
    private void setShowAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }
        if (null != mShowAnimation) {
            mShowAnimation.cancel();
        }
        mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
        mShowAnimation.setDuration(duration);
        // mShowAnimation.setFillAfter(true);
        mShowAnimation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                view.clearAnimation();
            }
        });
        view.startAnimation(mShowAnimation);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (hier > 1) {
                if (hier == 3) {
                    setHideAnimation(relSpecial, 500);
                    hier = 2;
                    auctionInfo = "拍卖行(" + pmlist.size() + ")";
                    catalog.setText(organizationInfo + "/" + auctionInfo);
                } else if (hier == 2) {
                    setHideAnimation(relAuction, 500);
                    hier = 1;
                    organizationInfo = "机构(" + list.size() + ")";
                    catalog.setText(organizationInfo);
                }
            } else {
                finish();
            }
        }

        return false;

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String length = data.getString("length");

            // 处理下载读取长度为-1 问题
            // 获取文件大小

            String name = organizationID + auctionID + workcoi.getId();
            String path = DownloadUtil.baseUrl + name + ".zip";
            Map<String, String> map = new HashMap<String, String>();
            map.put("name", name);
            map.put("title", workcoi.getTitle());
            map.put("info",
                    workcoi.getSeller_name() + "\n拍卖时间："
                            + workcoi.getAuction_start_time() + "-"
                            + workcoi.getAuction_end_time());
            map.put("imgurl", workcoi.getImgurl());
            map.put("htmlurl", workcoi.getHtmlurl());
            map.put("zipurl", workcoi.getZipurl());
            map.put("localurl", path);
            map.put("progress", "0");
            map.put("size", String.valueOf(length));
            CatalogueBean cb = new CatalogueBean(map);
            DbManager db = x.getDb(((ArtToGoApp) getApplication()).getDaoConfig());
            try {
                db.save(cb);
                System.out.println("创建数据表");

                // CatalogueBean cata = new CatalogueBean();
                // cata.setId(1);
                // cata.setProgress(String.valueOf(22));
                // db.update(cata, "progress");

                Selector<CatalogueBean> selector = db
                        .selector(CatalogueBean.class);
                // 如果要使用条件查询的话可以使用
                // Selector<user> selector =
                // db.selector(User.class).where("id","=",id).and("age",">",10);
                List<CatalogueBean> all = selector.findAll();
                System.out.println("all=" + all.toString());
            } catch (DbException e) {
                System.out.println("save failure:" + e.getMessage());
            }
            DownloadUtil.getInstance().httpDownLoad(path, workcoi.getZipurl(),
                    true);
            Toast.makeText(mContext, "已添加到我的图录下载队列", Toast.LENGTH_LONG).show();

            // TODO
            // UI界面的更新等相关操作
        }
    };

    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            // 在这里进行 http request.网络请求相关操作
            // 创建连接
            URL url;
            int length = 0;
            try {
                url = new URL(workcoi.getZipurl());
                // 根据响应获取文件大小
                HttpURLConnection urlcon = (HttpURLConnection) url
                        .openConnection();
                // 获取相应的文件长度
                length = urlcon.getContentLength();
                System.out.println("length=" + length);
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("length", length + "");
            msg.setData(data);
            handler.sendMessage(msg);
        }
    };

    public boolean fileIsExists(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }
}
